import type { UserConfig } from 'vite';
import { defineConfig, loadConfigFromFile, mergeConfig } from 'vite';
import reactRefresh from '@vitejs/plugin-react-refresh';
import seepln from './vitePluginSeepln';
import seeplnAntd from 'vite-plugin-seepln-antd';
import seeplnIcon from 'vite-plugin-seepln-icon';
import type { RollupReplaceOptions } from '@rollup/plugin-replace';
import type { BuildOptions } from './build';

export interface SeepflyConfig {
  /**
   * ant-design 样式前缀
   */
  antPrefix?: string;
  /**
   * 打包目标：系统/组件
   */
  target?: 'element';
  /**
   * 主题配置，postcss 中 modifyVars 参数
   */
  theme?: Record<string, string>;
  /**
   * 是否生成可视化分析
   * @default false
   */
  analyze?: boolean;
  /**
   * Rollup 插件 replace 参数
   */
  replace?: RollupReplaceOptions;
  /**
   * 针对 Pact 调试，需"调用/提供"应用都开启
   */
  pactMode?: boolean;
}

export interface SeepflyUserConfig extends UserConfig {
  seepfly?: SeepflyConfig;
}

/**
 * viteConfig 适配器
 */
export function defineViteConfig(cfg: SeepflyUserConfig): SeepflyUserConfig {
  const { seepfly: { target, ...restSeepfly } = {} } = cfg;
  // https://vitejs.dev/config/
  return defineConfig({
    ...cfg,
    plugins: [
      reactRefresh(),
      seepln({
        mode: target || 'system',
        ...restSeepfly,
      }),
      seeplnAntd(),
      seeplnIcon(),
      ...(cfg.plugins ? [...cfg.plugins] : []),
    ],
  }) as SeepflyUserConfig;
}

/**
 * 转换 vite 配置 至 seepfly
 */
export async function resolveViteConfig(inlineConfig: BuildOptions): Promise<BuildOptions> {
  const cfg = await loadConfigFromFile({
    mode: 'production',
    command: 'build',
  });

  if (!cfg) {
    return inlineConfig;
  }
  const userConfig = cfg.config as SeepflyUserConfig;

  return mergeConfig(
    {
      base: userConfig.base,
      mode: userConfig.mode,
      alias: userConfig.resolve?.alias,
      ...userConfig.seepfly,
      sourcemap: userConfig.build?.sourcemap,
      rollupOptions: userConfig.build?.rollupOptions,
    },
    inlineConfig,
  ) as BuildOptions;
}
